package com.xxl.job.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.schedule.XxlJobDynamicScheduler;
import com.xxl.job.admin.dao.JawsJobGovernDao;
import com.xxl.job.admin.dao.XxlJobInfoDao;
import com.xxl.job.admin.service.JawsJobGovernService;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * xxl job  执行器服务实现类`
 *
 * @author liangqm
 * @date 2018/7/23 8:15
 * @since v1.0.0
 */
@Service
public class JawsJobGovernServiceImpl implements JawsJobGovernService {
	private Logger logger = LoggerFactory.getLogger(JawsJobGovernServiceImpl.class);

	@Resource
	private JawsJobGovernDao jawsJobGovernDao;

	@Resource
	private XxlJobInfoDao xxlJobInfoDao;

	@Override
	public Integer obtainJobExecutorId(XxlJobGroup xxlJobGroup) {
		Integer groupId = jawsJobGovernDao.findGroupByName(xxlJobGroup.getAppName());

		if (groupId == null || groupId < 1) {
			// 插入执行器
			try {
				int result = jawsJobGovernDao.saveXxlJobGroup(xxlJobGroup);
				if (result > 0) {
					groupId = xxlJobGroup.getId();
				}
			} catch (Exception e) {
				logger.error("obtainJobExecutorId ==> {}", e);
				throw new RuntimeException(e);
			}
		} else {
			// 执行器存在,更新
			xxlJobGroup.setId(groupId);
			try {
				jawsJobGovernDao.updateXxlJobGroup(xxlJobGroup);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		logger.info("{} groupID ==> {} ", xxlJobGroup.getAppName(), groupId);
		return groupId;
	}

	@Override
	public XxlJobInfo registerJob(XxlJobInfo xxlJobInfo) {
		// groupId 和 执行器名称 查询
		XxlJobInfo jobHandlerInfo = jawsJobGovernDao.findJobHandler(xxlJobInfo.getJobGroup(), xxlJobInfo.getExecutorHandler());

		if (jobHandlerInfo == null) {
			// 插入xxlJobInfo 入库
			jawsJobGovernDao.saveJobHandler(xxlJobInfo);

			// add in quartz
			String qzGroup = String.valueOf(xxlJobInfo.getJobGroup());
			String qzName = String.valueOf(xxlJobInfo.getId());
			try {
				XxlJobDynamicScheduler.addJob(qzName, qzGroup, xxlJobInfo.getJobCron());
			} catch (SchedulerException e) {
				logger.error("registerJob XxlJobDynamicScheduler addJob ==>{}", e);
				// XXL_JOB_QRTZ_TRIGGERS 插入失败后，删除 xxlJobInfo
				try {
					xxlJobInfoDao.delete(xxlJobInfo.getId());
					XxlJobDynamicScheduler.removeJob(qzName, qzGroup);
				} catch (SchedulerException e1) {
					logger.error("registerJob XxlJobDynamicScheduler removeJob ==>{}", e);
					throw new RuntimeException(e);
				}
			}

		} else {
			// 更新
			xxlJobInfo.setId(jobHandlerInfo.getId());
			jawsJobGovernDao.updateJobHandler(xxlJobInfo);

			// fresh quartz
			String qzGroup = String.valueOf(jobHandlerInfo.getJobGroup());
			String qzName = String.valueOf(jobHandlerInfo.getId());
			try {
				boolean ret = XxlJobDynamicScheduler.rescheduleJob(qzGroup, qzName, jobHandlerInfo.getJobCron());
				if (ret == false) {
					throw new RuntimeException(String.format("刷新任务失败, jobInfo ==> {}", JSON.toJSONString(jobHandlerInfo)));
				}
			} catch (SchedulerException e) {
				logger.error(e.getMessage(), e);
			}
		}

		return xxlJobInfo;
	}
}
